package weatherwidget.isrefluxer.bird.com.birdweatherwidget.data;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.Settings;
import android.text.TextUtils;

import java.util.ArrayList;

import weatherwidget.isrefluxer.bird.com.birdweatherwidget.constant.WeatherConstant;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.until.DateUtil;
import weatherwidget.isrefluxer.bird.com.birdweatherwidget.until.LogUtil;

/**
 * Created by Administrator on 2016/11/20 0020.
 */

public class DatabaseHelper {

    private static final String TAG = "DatabaseHelper";


    private static final  Uri uri_citys =  Uri.parse("content://com.birdweather.weatherservice/citys");
    private static Uri uri_weather =  Uri.parse("content://com.birdweather.weatherservice/weather");

    public synchronized static String getLocalCity(Context context) {
        ContentResolver cr = context.getContentResolver();
        Cursor c = null;
        try
        {
            c = cr.query(uri_citys,new String[]{
                    "city_name"
            },
                    "isLocal=?",new String[]{
                            "1"
                    },null);
            if(c!=null && c.moveToNext()){
                return c.getString(0);
            }
        }catch (Exception e){

        }finally {
            if(c!=null)
                c.close();
        }
             return  null;

    }

    public static WeatherInfo getTodayData(Context context, String locaCity) {

        WeatherInfo weatherInfo = null;
        LogUtil.log(TAG,"getTodayData(locaCity): "+(locaCity)+" date: "+DateUtil.getYYYY_MM_DD(System
                                    .currentTimeMillis()));
        if (locaCity == null)
            return weatherInfo;
        ContentResolver cr = context.getContentResolver();
        Cursor c = null;
        try {
            c = cr.query(
                    uri_weather,
                    null,
                    "city_name=? and date=?",
                //    null,
                    new String[] {
                            locaCity,
                            DateUtil.getYYYY_MM_DD(System
                                    .currentTimeMillis())
                    },
                   // null,
                    null);
            LogUtil.log(TAG,"getTodayData(c.getCount()): "+(c.getCount()));

            LogUtil.log(TAG,"getTodayData(c!=null): "+(c!=null));
            LogUtil.log(TAG,"getTodayData( c.moveToNext()): "+( c.moveToNext()));
            if(c!=null && c.moveToNext()){

                weatherInfo = new WeatherInfo();
                LogUtil.log(TAG,"getTodayData(DATE): "+(c.getString(c.getColumnIndex(WeatherInfo.DATE))));
                LogUtil.log(TAG,"getTodayData(CITY_NAME): "+(c.getString(c.getColumnIndex(WeatherInfo.CITY_NAME))));
                LogUtil.log(TAG,"getTodayData(NOWTEMPER): "+(c.getString(c.getColumnIndex(WeatherInfo.NOWTEMPER))));
                weatherInfo.setValueByKey(WeatherInfo.CITY_ID,
                        c.getString(c.getColumnIndex(WeatherInfo.CITY_ID)));
                weatherInfo.setValueByKey(WeatherInfo.CITY_NAME,
                        c.getString(c.getColumnIndex(WeatherInfo.CITY_NAME)));
                weatherInfo.setValueByKey(WeatherInfo.DATE,
                        c.getString(c.getColumnIndex(WeatherInfo.DATE)));
                weatherInfo.setValueByKey(WeatherInfo.LAST_UPDATE,
                        c.getString(c.getColumnIndex(WeatherInfo.LAST_UPDATE)));
                weatherInfo.setValueByKey(WeatherInfo.NOWTEMPER,
                        c.getString(c.getColumnIndex(WeatherInfo.NOWTEMPER)));
                weatherInfo.setValueByKey(WeatherInfo.MAXTEMPER,
                        c.getString(c.getColumnIndex(WeatherInfo.MAXTEMPER)));
                weatherInfo.setValueByKey(WeatherInfo.MINTEMPER,
                        c.getString(c.getColumnIndex(WeatherInfo.MINTEMPER)));
                weatherInfo.setValueByKey(WeatherInfo.AQI,
                        c.getString(c.getColumnIndex(WeatherInfo.AQI)));
                weatherInfo.setValueByKey(WeatherInfo.PM2D5,
                        c.getString(c.getColumnIndex(WeatherInfo.PM2D5)));
                weatherInfo.setValueByKey(WeatherInfo.WEATHER_DAY,
                        c.getString(c.getColumnIndex(WeatherInfo.WEATHER_DAY)));
                weatherInfo
                        .setValueByKey(WeatherInfo.WEATHER_NIGHT, c.getString(c
                                .getColumnIndex(WeatherInfo.WEATHER_NIGHT)));
                weatherInfo.setValueByKey(WeatherInfo.WIND_DIRECTION,
                        c.getString(c
                                .getColumnIndex(WeatherInfo.WIND_DIRECTION)));
                weatherInfo.setValueByKey(WeatherInfo.WIND_POWER,
                        c.getString(c.getColumnIndex(WeatherInfo.WIND_POWER)));
                weatherInfo.setValueByKey(WeatherInfo.WIND,
                        c.getString(c.getColumnIndex(WeatherInfo.WIND)));


            }
        }catch (Exception e) {
            LogUtil.log(TAG,"getTodayData(Exception): "+e.toString());
        } finally {
            if (c!= null) {
                c.close();
            }
        }
        return  weatherInfo;

    }

    public synchronized static String[] getCitys(Context context) {
        String[] citys = null;
        ContentResolver cr = context.getContentResolver();
        Cursor c = null;
        try {
            c = cr.query(uri_citys, new String[] {
                            "city_name", "isLocal"
                    },
                    null, null, null);
            citys = new String[c.getCount()];
            int i = 0;
            String temp;
            while (c != null && c.moveToNext()) {
                if ("1".equals(c.getString(1)) && i > 0) {
                    temp = citys[0];
                    citys[0] = c.getString(0);
                    citys[i++] = temp;
                } else {
                    citys[i++] = c.getString(0);
                }
            }
        }catch (Exception e) {
        } finally {
            if (c != null) {
                c.close();
            }
        }

        return citys;

    }

    public synchronized static void deleteOldWeathers(Context context) {
        ContentResolver cr = context.getContentResolver();
        String date_5_ago = DateUtil.getYYYY_MM_DD(System.currentTimeMillis()- 5 * 24 * 60 * 60 * 1000);
        cr.delete(uri_weather,WeatherInfo.DATE+" < ?",new String[]{date_5_ago});

    }

    public synchronized static void writeWeather(Context context, ArrayList<WeatherInfo> weaherInfos) {

        if(weaherInfos == null)
            return;
        LogUtil.log(TAG,"writeWeather start");
        ContentResolver cr = context.getContentResolver();
        ContentValues contentValues = new ContentValues();
        int update=0;

        for (WeatherInfo wi:weaherInfos) {
            LogUtil.log(TAG,wi.getValueByKey(WeatherInfo.CITY_NAME));
            LogUtil.log(TAG,wi.getValueByKey(WeatherInfo.CITY_ID));
            LogUtil.log(TAG,wi.getValueByKey(WeatherInfo.DATE));
            LogUtil.log(TAG,wi.getValueByKey(WeatherInfo.WEATHER_DAY));
            LogUtil.log(TAG,wi.getValueByKey(WeatherInfo.WIND_DIRECTION));
            LogUtil.log(TAG,wi.getValueByKey(WeatherInfo.WIND_POWER));
            LogUtil.log(TAG,wi.getValueByKey(WeatherInfo.WIND));
            LogUtil.log(TAG,wi.getValueByKey(WeatherInfo.NOWTEMPER));
            contentValues.put(WeatherInfo.CITY_ID,
                    wi.getValueByKey(WeatherInfo.CITY_ID));
            if ( wi.getValueByKey(WeatherInfo.CITY_NAME)!=null &&
                    wi.getValueByKey(WeatherInfo.CITY_NAME).endsWith("市") &&  wi.getValueByKey(WeatherInfo.CITY_NAME).length() > 2) {

                contentValues.put(WeatherInfo.CITY_NAME,
                        wi.getValueByKey(WeatherInfo.CITY_NAME).substring(0,  wi.getValueByKey(WeatherInfo.CITY_NAME).length() - 1));

            }
            else
                contentValues.put(WeatherInfo.CITY_NAME,
                        wi.getValueByKey(WeatherInfo.CITY_NAME));
            if ( wi.getValueByKey(WeatherInfo.DATE)!=null)
                contentValues.put(WeatherInfo.DATE,
                        wi.getValueByKey(WeatherInfo.DATE).split(" ")[0]);

            contentValues.put(WeatherInfo.WEATHER_DAY,
                    wi.getValueByKey(WeatherInfo.WEATHER_DAY));
            contentValues.put(WeatherInfo.WIND_DIRECTION,
                    wi.getValueByKey(WeatherInfo.WIND_DIRECTION));
            contentValues.put(WeatherInfo.WIND_POWER,
                    wi.getValueByKey(WeatherInfo.WIND_POWER));
            contentValues.put(WeatherInfo.WIND,
                    wi.getValueByKey(WeatherInfo.WIND));
            contentValues.put(WeatherInfo.NOWTEMPER,
                    wi.getValueByKey(WeatherInfo.NOWTEMPER));
            LogUtil.log(TAG,"update: "+update);

            update = cr
                    .update(uri_weather,
                            contentValues,
                            WeatherInfo.CITY_NAME + "=? and "
                                    + WeatherInfo.DATE + "=?",
                            new String[] {
                                    wi.getValueByKey(WeatherInfo.CITY_NAME),
                                    wi.getValueByKey(WeatherInfo.DATE)
                            });
            LogUtil.log(TAG,"update: "+update);
            if (update <= 0) {
                cr.insert(uri_weather, contentValues);
            }
            LogUtil.log(TAG,"writeWeather end");
            contentValues.clear();

        }
    }

    public synchronized static void insertCity(Context context, String city,
                                               String cityId, String isLocal) {
        if(city == null){
            return;
        }
        ContentResolver cr = context.getContentResolver();
        ContentValues contentvalues = new ContentValues();
        contentvalues.put(WeatherInfo.CITY_ID, cityId);
        contentvalues.put(WeatherInfo.CITY_NAME, city);
        String localCity = getLocalCity(context);
        if (TextUtils.isEmpty(localCity)) {
            contentvalues.put(WeatherInfo.ISLOCAL, "1");
        } else {
            contentvalues.put(WeatherInfo.ISLOCAL, isLocal);
        }
        cr.delete(uri_citys, "city_name=?", new String[] {
                city
        });
        if ("1".equals(isLocal)) {
            cr.delete(uri_citys, "isLocal=?", new String[] {
                    "1"
            });
        }

        cr.insert(uri_citys, contentvalues);

    }

    public synchronized static String getUpdateTime(Context context) {
        ContentResolver cr = context.getContentResolver();
        Cursor c = null;
        try {
              c = cr.query(uri_weather,new String[]{
                    WeatherInfo.DATE
              }, "date=? and city_name=?", new String[] {
                      DateUtil.getYYYY_MM_DD(System.currentTimeMillis()),
                      getLocalCity(context)},null);
            if (c != null && c.moveToNext()) {
                return c.getString(0);

            }
        }catch (Exception e) {
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return null;
    }

    public synchronized static boolean isLocalCity(Context context, String city) {
        ContentResolver cr = context.getContentResolver();
        Cursor c = null;
        try {
            c = cr.query(uri_citys, new String[] {
                            "isLocal"
                    }, "city_name=?",
                    new String[] {
                            city
                    }, null);
            if (c != null && c.moveToNext()) {
                String isLocal = c.getString(0);
                return "1".equals(isLocal) ? true : false;
            } else {
                return false;
            }
        } catch (Exception e) {
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return false;
    }
}
